
package com.eworking.eim.database;

import java.util.ArrayList;
import java.util.List;

import com.eworking.eim.group.EIMGroupTable;
import com.eworking.eim.message.EIMMessageTable;
import com.eworking.eim.user.EIMUserTable;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class EIMDatabaseManager extends SQLiteOpenHelper {
    
    /** 数据库名称 */
    private static final String _DATABASE_NAME = "eworking-im.db";
    
    /** 数据库版本 */
    private static final int _DATABASE_VERSION = 1;
    
    private static EIMDatabaseManager databaseManager = null;
    
    /** 所有表数据操作类集合 */
    private final List<EIMDatabaseTable> databaseTables;
    
    public EIMDatabaseManager(Context context, String username) {
        super(context, username + "_" + _DATABASE_NAME, null, _DATABASE_VERSION);
        databaseTables = new ArrayList<EIMDatabaseTable>();
        databaseManager = this;
        this.initAddTables();
    }
    
    private void initAddTables() {
        this.addTable(new EIMUserTable(this));
        this.addTable(new EIMGroupTable(this));
        this.addTable(new EIMMessageTable(this));
    }
    
    public static EIMDatabaseManager getInstance() {
        return databaseManager;
    }
    
    public void addTable(EIMDatabaseTable databaseTable) {
        this.databaseTables.add(databaseTable);
    }
    
    @Override
    public void onCreate(SQLiteDatabase db) {
        // 创建表
        for (EIMDatabaseTable databaseTable : this.databaseTables) {
            databaseTable.onCreated(db);
        }
    }
    
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 删除表
        for (EIMDatabaseTable databaseTable : this.databaseTables) {
            databaseTable.onDroped(db);
        }
        // 重新创建
        onCreate(db);
    }
    
    /**
     * 关闭数据库连接
     */
    public void closeDatabase() {
        this.close();
    }
    
}
